<template>
  <div>
     <canvas id="can"
            width="150"
            height="40"
            @click="changeVeri()"></canvas>
  </div>
</template>
<script lang="ts">
import {defineComponent,HtmlHTMLAttributes,reactive,ref, toRefs} from 'vue'
import {getVeri} from '../../api/login'
interface datasFace{
  code:string,
  changeVeri():void,
  makeVeri():void,
  ranDom(a:number,b:number):number,
  draw():void,
  ranColor():string
}
export default defineComponent({
        setup(){
          
            let datas:datasFace=reactive({
                code:"",//验证码
                changeVeri: ()=> {//点击获取验证码
                  datas.makeVeri(); //点击切换验证码
                },
                async makeVeri (){//获取验证码
                    var res:any=await getVeri()
                    console.log(res)
                    datas.code=res.data;
                    datas.draw();//绘制验证码方法
                 },
                // 随机函数
                ranDom :(a, b)=> { //a-b之间的随机数
                  return Math.floor(Math.random() * (b - a + 1) + a)
                },
                // 随机颜色
                ranColor :()=> {
                  return "#" + Math.floor(Math.random() * 0xFFFFFF).toString(16)
                },
               draw () { //绘制验证码方法
              //  
               var can=document.getElementById("can");
                var c:any =(can as HTMLCanvasElement).getContext("2d");
                // 清空画布
                c.clearRect(0, 0, 150, 40);
                // 绘制干扰线
                // for (var i = 0; i < 20; i++) {
                //   c.beginPath()
                //   c.moveTo(this.ranDom(0, 150), this.ranDom(0, 40))
                //   c.lineTo(this.ranDom(0, 150), this.ranDom(0, 40))
                //   c.strokeStyle = this.ranColor();
                //   c.stroke();
                // }
                // 绘制干扰点
                // for (var y = 0; y < 30; y++) {
                //   c.beginPath()
                //   var lx = this.ranDom(0, 150);
                //   var ly = this.ranDom(0, 40);
                //   c.moveTo(lx, ly)
                //   c.lineTo(lx + 1, ly + 1)
                //   c.strokeStyle = this.ranColor();
                //   c.stroke();
                // }
                // 绘制文本
                // c.rotate(this.ranDom(-5, 5) * Math.PI / 180);
                for (var k = 0; k < datas.code.length; k++) {
                  c.font = "25px 黑体";
                  c.fillText(datas.code[k], 30 * k + datas.ranDom(5, 20), datas.ranDom(20, 30))
                  c.fillStyle = datas.ranColor();
                  c.stroke()
                }
              }
        })
        datas.makeVeri();//首次加载就获取
        var mydata=toRefs(datas)
        return {
            ...mydata
        }
    }
})
</script>
<style lang="less" scoped> 
      canvas{
        background: skyblue;
      }
</style>